using System;
using System.Collections.Generic;
using UnityEngine;

namespace Framework.Event
{
    public class EventArgsList : EventArgs, IDisposable
    {
        private bool disposed = false;
        private List<object> mArgsList = new List<object>();

        public int Count => mArgsList.Count;
        public bool HasData => mArgsList.Count > 0;

        public EventArgsList() { }

        public EventArgsList(params object[] pArgs)
        {
            if (pArgs != null && pArgs.Length > 0)
            {
                mArgsList.AddRange(pArgs);
            }
        }

        public T GetDataByIndex<T>(int pIndex, T defaultValue = default(T))
        {
            if (disposed)
                throw new ObjectDisposedException(nameof(EventArgsList));

            if (pIndex < 0 || pIndex >= mArgsList.Count)
            {
                Debug.LogWarning($"EventArgsList index out of range. Index: {pIndex}, Count: {mArgsList.Count}");
                return defaultValue;
            }

            object value = mArgsList[pIndex];

            if (value is T typedValue)
            {
                return typedValue;
            }

            Debug.LogError($"Type mismatch in EventArgsList. Expected: {typeof(T).Name}, Actual: {value?.GetType().Name ?? "null"} at index {pIndex}");
            return defaultValue;
        }

        public bool TryGetDataByIndex<T>(int pIndex, out T result)
        {
            result = default(T);

            if (disposed || pIndex < 0 || pIndex >= mArgsList.Count)
                return false;

            object value = mArgsList[pIndex];
            if (value is T typedValue)
            {
                result = typedValue;
                return true;
            }

            return false;
        }

        /// <summary>添加数据</summary>
        public void AddData(object data)
        {
            if (disposed)
                throw new ObjectDisposedException(nameof(EventArgsList));

            mArgsList.Add(data);
        }

        /// <summary>批量添加数据</summary>
        public void AddRange(params object[] data)
        {
            if (disposed)
                throw new ObjectDisposedException(nameof(EventArgsList));

            if (data != null)
            {
                mArgsList.AddRange(data);
            }
        }

        /// <summary>清空数据</summary>
        public void Clear()
        {
            mArgsList.Clear();
        }

        public void Dispose()
        {
            if (!disposed)
            {
                mArgsList.Clear();
                disposed = true;
            }
        }
    }
}